﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "Tree.h"

BTNode* BTNodeInit(BTDataType x)
{
	BTNode* newNode = (BTNode*)malloc(sizeof(BTDataType));
	if (newNode == NULL)
	{
		perror("malloc fail!");
		exit(-1);
	}
	newNode->val = x;
	newNode->left = NULL;
	newNode->right = NULL;
	return newNode;
}

//前序遍历
void PreOrder(BTNode* root)
{
	if (root == NULL) return;
	printf("%d ", root->val);
	PreOrder(root->left);
	PreOrder(root->right);
}
//中序遍历
void InOrder(BTNode* root)
{
	if (root == NULL) return;
	InOrder(root->left);
	printf("%d ", root->val);
	InOrder(root->right);
}
//后序遍历 
void PostOrder(BTNode* root)
{
	if (root == NULL) return;
	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d ", root->val);
}

// ⼆叉树结点个数
int BinaryTreeSize(BTNode* root)
{
	if (root == NULL) return 0;
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}
//// ⼆叉树结点个数
//void BinaryTreeSize(BTNode* root, int* psize);

// ⼆叉树叶⼦结点个数
int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL) return 0;
	if (root->left == NULL && root->right == NULL) return 1;
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

// ⼆叉树第k层结点个数
int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL) return 0;
	if (k == 1) return 1;
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

//⼆叉树的深度/⾼度
int BinaryTreeDepth(BTNode* root)
{
	if (root == NULL) return 0;
	return BinaryTreeDepth(root->left) > BinaryTreeDepth(root->right) ? 1 + BinaryTreeDepth(root->left) : 1 + BinaryTreeDepth(root->right);
}

// ⼆叉树查找值为x的结点
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL) return NULL;
	if (root->val == x) return root;
	BTNode* leftFind = BinaryTreeFind(root->left, x);
	if (leftFind != NULL)
	{
		return leftFind;
	}
	BTNode* rightFind = BinaryTreeFind(root->right, x);
	if (rightFind != NULL)
	{
		return rightFind;
	}
	return NULL;
}

// ⼆叉树销毁
void BinaryTreeDestory(BTNode** root)
{
	if (*root == NULL) return;
	BinaryTreeDestory(&(*root)->left);
	BinaryTreeDestory(&(*root)->right);
	free(*root);
	*root = NULL;
}

//层序遍历
void LevelOrder(BTNode* root)
{

}

//判断二叉树是否为完全二叉树
bool BinaryTreeComplete(BTNode* root);